﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BuXiaChu.OrderDishes.BLL.WebRuntime;
using BuXiaChu.OrderDishes.BLL;
using BuXiaChu.OrderDishes.Model;
using BuXiaChu.OrderDishes.BLL.ModelExtensions;
using BuXiaChu.OrderDishes.BLL.CookieManager;

namespace BuXiaChu.OrderDishes.Web.CallCenter.Order
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Order : HttpHandlerBase, IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            base.Init(context);

            var t = GetFormValue("t");
            switch (t)
            {
                case "2":
                    Add();
                    break;
                default:
                    AjaxActionResult result = new AjaxActionResult();
                    result.message = "未知的操作 t:" + t;
                    SerializeDataToResponseStream(result);
                    break;
            }
        }

        private void Add()
        {
            #region
            AjaxActionResult result = new AjaxActionResult();
            try
            {
                UserInfoModel userInfo = new UserInfoModel();
                DeliveryAddressModel addressInfo = new DeliveryAddressModel();
                if (CollectUserInfo(userInfo) && UserInfoManager.Save(userInfo))
                {
                    addressInfo.GetUserInfoFrom(userInfo);
                    if (CollectAddressInfo(addressInfo) && DeliveryAddressManager.Save(addressInfo))
                    {
                        OrderInfoModel orderInfo = new OrderInfoModel();
                        orderInfo.GetAddressInfoFrom(addressInfo);

                        List<OrderItemModel> orderItemList = new List<OrderItemModel>();
                        if (CollectOrderInfo(orderInfo, orderItemList))
                        {
                            result.success = OrderInfoManager.Save(orderInfo, orderItemList);
                        }
                    }
                }
                else
                {
                    result.message = "信息填写不完整";
                }

            }
            catch (Exception ex)
            {
                ExceptionMessageManager.Record(ex);
            }

            SerializeDataToResponseStream(result);
            #endregion
        }

        private bool CollectUserInfo(UserInfoModel userInfo)
        {
            #region
            userInfo.UserId = int.Parse(GetFormValue("userId"));
            userInfo.MobileTelephone = GetFormValue("mobile");
            userInfo.Telephone = GetFormValue("tel");
            userInfo.Gender = byte.Parse(GetFormValue("gender"));
            userInfo.Name = GetFormValue("name");
            if (string.IsNullOrEmpty(userInfo.Name)
                || (string.IsNullOrEmpty(userInfo.MobileTelephone) && string.IsNullOrEmpty(userInfo.Telephone)))
            {
                return false;
            }
            return true;
            #endregion
        }

        private bool CollectAddressInfo(DeliveryAddressModel addressInfo)
        {
            #region
            addressInfo.Id = int.Parse(GetFormValue("addressId"));
            addressInfo.CityId = int.Parse(GetFormValue("cityId"));
            addressInfo.AreaId = int.Parse(GetFormValue("areaId"));
            addressInfo.Address = GetFormValue("address");
            addressInfo.InvoiceTitle = GetFormValue("invoicTitle");

            return string.IsNullOrEmpty(addressInfo.Address) ? false : true;
            #endregion
        }

        private bool CollectOrderInfo(OrderInfoModel orderInfo, List<OrderItemModel> orderItemList)
        {
            #region
            orderInfo.Freight = decimal.Parse(GetFormValue("freight"));
            orderInfo.LatestTime = DateTime.Parse(GetFormValue("lastTime"));
            orderInfo.TelephoneOperator = LoginSysUserInfo.Intance.EmploeeId;
            var key = "";
            var idString = "";

            foreach (var item in Request.Form.Keys)
            {
                OrderItemModel orderItem = new OrderItemModel();
                key = item.ToString();
                if (key.ToLower().IndexOf("dishesid_") >= 0)
                {
                    idString = key.Split('_')[1];
                    orderItem.DishesId = long.Parse(idString);
                    orderItem.DishesName = GetFormValue("dishesName_" + idString);
                    orderItem.Number = int.Parse(GetFormValue(key));
                    orderItem.Price = decimal.Parse(GetFormValue("price_" + idString));
                    orderItem.Remarks = GetFormValue("remarks_" + idString);
                    orderItem.RestaurantId = int.Parse(GetFormValue("restaurantId_" + idString));
                    orderItem.RestaurantName = GetFormValue("restaurantName_" + idString);
                    orderItem.Unit = int.Parse(GetFormValue("unit_" + idString));
                    orderItem.Box = byte.Parse(GetFormValue("boxNum_" + idString));
                    orderItem.BoxUnitPrice = decimal.Parse(GetFormValue("boxPrice_" + idString));
                    orderInfo.Total += orderItem.Number * orderItem.Price;
                    orderInfo.Total += orderItem.Box * orderItem.BoxUnitPrice;//餐盒

                    if (!string.IsNullOrEmpty(orderInfo.InvoiceTitle))
                    {
                        orderItem.Discount = int.Parse(GetFormValue("discount_" + idString));
                    }
                    else
                    {
                        orderItem.Discount = int.Parse(GetFormValue("invoiceDiscount_" + idString));
                    }
                    orderItemList.Add(orderItem);
                }
            }

            return orderItemList.Count > 0 ? true : false;
            #endregion
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
